package com.sogoodsoft.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sogoodsoft.entity.app.Organization;
import com.sogoodsoft.service.app.OrganizationService;
import com.sogoodsoft.web.WebConstants;

public class InfosysUtils {

	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static SimpleDateFormat yyyy = new SimpleDateFormat("yyyy");
	public static SimpleDateFormat MM = new SimpleDateFormat("MM");
	public static SimpleDateFormat YMD = new SimpleDateFormat("yyyy-MM-dd");
	private static Logger logger = LoggerFactory.getLogger(InfosysUtils.class);
	public static String translatePath(String path){
		URL url = InfosysUtils.class.getResource("/");
		String rtn = url.toString();		
		try {
			url = new URL(url,"../"+path);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		rtn = url.toString();
		rtn =rtn.replace("file:/", "");
		return rtn;
	}
	
	/**
	 * 返回当前 年月日时分秒
	 * 如：20110611140526
	 * @param title
	 * @return
	 */
	public static String getNow(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		return sdf.format(new Date());
	}
	public static String YMD(Date date){
		return YMD.format(date);
	}
	
	public static String getAbosluteFilePath(String path){
		String filePath = "";
		filePath = WebConstants.DOC_DIR+path;
		filePath = translatePath(path);		
		return filePath;
	}
	
	public static String getAbsoluteDocDir(){
		URL url = InfosysUtils.class.getResource("/");		
		String rtn = url.toString();		
		try {
			url = new URL(url,"../.."+WebConstants.DOC_DIR);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		rtn = url.toString();
		rtn =rtn.replace("file:/", "");
		return rtn;
		
	}
	/**
	 * 传入字符形式日期时间yyyy-MM-dd HH:mm:ss
	 * 返回Date
	 * @param datetime
	 * @return
	 */
	public static Date castDatetime(String datetime){
		Date  dt = null;		
		try {
			if(datetime!=null&&datetime.length()>0){
			dt = sdf.parse(datetime);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return dt;
	}
	
	public static String getYear(Date date){
		return yyyy.format(date);
	}
	public static String getMonth(Date date){
		return MM.format(date);
	}
	public static String StringJS(String js){
		String str = js;
		str = str.replace("\"","\\\"");
		str = str.replace("\'", "\\'");
		str = str.replace("\n","\\n");
		return str;
	}
	
	public static String getExceptionStackTrace(Exception e){
		StringWriter writer = new StringWriter();
		PrintWriter printWriter = new PrintWriter(writer);
		e.printStackTrace(printWriter);
		return writer.getBuffer().toString();
	} 
	
	public static String dateFormat(Date date){
		String dt = "";
		dt = sdf.format(date);
		return dt;
	}
	
	public static String getOrgRoot(HttpServletRequest request){
		OrganizationService orgService = (OrganizationService)InfoSpringUtil.getBean(request, "organizationService");
		Organization org = orgService.getRoot();
		return org.name;
	}
	
	public static Properties prop(String fileName){
		File file  = new File(translatePath(fileName));
		Properties prop = new Properties();
		try {
			if(!file.exists()){
				file.createNewFile();
			}
			prop.load(new FileInputStream(file));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return prop;
	}
	
	public static String prop(String key,String fileName){
		return prop(fileName).getProperty(key);
	}
	public static void store(Properties prop,String fileName){
		try {
			FileOutputStream out = new FileOutputStream(translatePath(fileName));
			prop.store(out, "");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static int weekOfYear(){
		int week = 0;
		Calendar calendar = Calendar.getInstance();
		week = calendar.get(Calendar.WEEK_OF_YEAR);
		return week;
	}
	
	 public static boolean exec(String cmd) throws Exception {
	        boolean success = true;
	        Runtime run = Runtime.getRuntime();
	        Process p = run.exec(cmd);// 启动另一个进程来执行命令
	        BufferedInputStream in = new BufferedInputStream(p.getInputStream());
	        BufferedInputStream err = new BufferedInputStream(p.getErrorStream());
	        BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
	        BufferedReader errBr = new BufferedReader(new InputStreamReader(err));
	        String lineStr;
	        while ((lineStr = errBr.readLine()) != null)
	            logger.debug(lineStr);
	        while ((lineStr = inBr.readLine()) != null)
	            logger.debug(lineStr);
	        // 检查命令是否执行失败。
	        if (p.waitFor() != 0) {
	            // p.exitValue()==0表示正常结束，1：非正常结束
	            if (p.exitValue() == 1) {
	                logger.debug("命令 " + cmd + " 执行失败!");
	                success = false;
	            }
	        }
	        return success;
	    }
	
	public static void main(String args[]){
		Properties val = prop(WebConstants.BACKUP_DB_RECORD);
		System.out.println(val.get("WEEK"));
		val.setProperty("WEEK", "3");
		store(val,WebConstants.BACKUP_DB_RECORD);
	}
}
